package dao;

import DBU.DBUtil;
import entity.Orders;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class OrdersDAOImp implements OrdersDAO{
    @Override
    public boolean addOrders(Orders orders) {
        Connection conn = DBUtil.getConnection();
        String sql = "insert into orders values(?,?,?,?,?,?,?,?) ";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,orders.getOid());
            ps.setString(2,orders.getTime());
            ps.setString(3, orders.getName());
            ps.setString(4, orders.getVariety());
            ps.setDouble(5, orders.getSum());
            ps.setString(6, orders.getConsignee());
            ps.setString(7, orders.getAddress());
            ps.setString(8, orders.getCphone());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public List<Orders> checkOrders() {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from flower";
        PreparedStatement ps = null;
        try {
            ps  = conn.prepareStatement(sql);
            ps.executeQuery();
            return (List<Orders>) ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override    //orders表字段oid  time  name  variety  sum  consignee  address  cphone
    public boolean buyFlower(int fid, int num, int cid, String consignee, String address, String cphone) {
        //time
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time = df.format(new Date());    //时间
        //variety  sum
        FlowerDAOImp flowerDAOImp = new FlowerDAOImp();
        List<String> listflower = flowerDAOImp.buyFlower(fid,num);   //第2，3位为品种和单价
        String variety = listflower.get(2);   //品种
        double price = Integer.valueOf(listflower.get(3));
        double sum = price*num;   //总价
        //name
        CustomerDAOImp customerDAOImp = new CustomerDAOImp();
        List<String> listcustomer = customerDAOImp.buyFlower(cid);     //第2位为姓名
        String name = listcustomer.get(2);    //姓名
        //生成随机数与手机号码组成订单编号     随机数+手机号
        Random r = new Random();
        int ran = r.nextInt(1000);
        String oid = ran+""+cphone;   //订单编号
        //操作数据库
        Connection conn = DBUtil.getConnection();
        String sql = "insert into orders (oid,time,name,variety,sum,consignee,adress,cphone) \n" +
                "values(oid,time,variety,sum,name,consignee,address,cphone);";
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.executeQuery();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
